//
//  DataBaseTools.m
//  MemoryTravel
//
//  Created by dllo on 15/12/26.
//  Copyright © 2015年 fcx. All rights reserved.
//

#import "DataBaseTools.h"

@interface DataBaseTools()

@property (nonatomic, strong)FMDatabase *db;

@end

@implementation DataBaseTools

//数据库存字典,需要将字典转成字符串,然后存入数据库中,取的时候先取出字符串,然后再转成解析成字典
//字典转成字符串
+ (NSString *)GetStringFromDictionary:(NSMutableDictionary *)dic{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    NSString *string = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    return string;
}

//字符串转成字典
+ (NSMutableDictionary *)GetDictionaryFromString:(NSString *)string{
    NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];
    NSMutableDictionary *myDictionary = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
    NSLog(@"字符串转成字典=====%@",myDictionary);
    return myDictionary;
}

//单例化
+ (instancetype)shareDataBase{
    static DataBaseTools *database = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        
        database = [[DataBaseTools alloc] init];
    });
    return database;
}
//打开数据库
- (void)openDB{
    if (self.db != nil) {
        NSLog(@"数据库已经打开");
    }
    else{
        NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
        NSString *fileName = [doc stringByAppendingPathComponent:@"MemoryTravel.sqlite"];
        self.db = [FMDatabase databaseWithPath:fileName];
        
        BOOL result = [self.db open];
        if (result) {
            NSLog(@"数据库打开完成");
        }
    }
}

//创建用户信息表
- (void)createMessage{
    BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS autoCarUserMessage(number INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT, password TEXT)"];
    if (result) {
        NSLog(@"创建表成功");
    }
    else {
        NSLog(@"创建表失败");
    }
}
//插入用户信息（名字，密码）
- (void)insertMessageWithUserName:(NSString *)userName password:(NSString *)password{
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO autoCarUserMessage(name, password) VALUES('%@', '%@')", userName, password];
    BOOL result = [self.db executeUpdate:sql];
    if (result) {
        NSLog(@"插入成功");
    }
    else {
        NSLog(@"插入失败");
    }
}
//查询用户信息，返回字典
- (NSMutableDictionary *)selectMessage{
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    //1.执行查询语句
    FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM autoCarUserMessage"];
    
    //遍历集合
    while ([resultSet next]) {
        NSString *name = [resultSet objectForColumnName:@"name"];
        NSString *password = [resultSet objectForColumnName:@"password"];
        [dic setObject:password forKey:name];
    }
    return dic;
}

#pragma mark - 尹凯、第三界面
//创建选择城市表
- (void)createCityChooseTbale{
    BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS cityChooseTable(number INTEGER PRIMARY KEY AUTOINCREMENT, type TEXT, data TEXT)"];
    if (result) {
        NSLog(@"创建表成功");
    }
    else {
        NSLog(@"创建表失败");
    }
}
//插入热门城市
- (void)insertHotCitiesWithArray:(NSMutableArray *)hotArray{
    NSString *data = [hotArray componentsJoinedByString:@","];
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO cityChooseTable(type, data) VALUES('%@', '%@')", @"热门", data];
    BOOL result = [self.db executeUpdate:sql];
    if (result) {
        NSLog(@"插入成功");
    }
    else {
        NSLog(@"插入失败");
    }
}
//插入全部城市
- (void)insertAllCitiesWithArray:(NSMutableArray *)allArray{
    NSString *data = [allArray componentsJoinedByString:@","];
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO cityChooseTable(type, data) VALUES('%@', '%@')", @"全部", data];
    BOOL result = [self.db executeUpdate:sql];
    if (result) {
        NSLog(@"插入成功");
    }
    else {
        NSLog(@"插入失败");
    }
}
//根据类型查找
- (NSMutableArray *)selectCityArrayWithType:(NSString *)type{
    NSMutableArray *array = nil;
    //1.执行查询语句
    FMResultSet *resultSet = [self.db executeQuery:[NSString stringWithFormat:@"SELECT * FROM cityChooseTable WHERE type = '%@'", type]];
    
    //遍历集合
    while ([resultSet next]) {
        NSString *data = [resultSet objectForColumnName:@"data"];
        array = [NSMutableArray arrayWithArray:[data componentsSeparatedByString:@","]];
    }
    return array;
}
//删除城市表
- (void)dropCityChooseTable{
    NSString *sql = @"DROP TABLE IF EXISTS cityChooseTable";
    BOOL result = [self.db executeUpdate:sql];
    if (result) {
        NSLog(@"删除成功");
    }
    else{
        NSLog(@"删除表失败");
    }
}

//创建收藏表
- (void)createExperienceTable{
    BOOL result = [self.db executeUpdate:@"CREATE TABLE IF NOT EXISTS experienceTableChange(number INTEGER PRIMARY KEY AUTOINCREMENT, title_page TEXT, title TEXT, date_str TEXT, address TEXT, like_count TEXT, price TEXT, product_id TEXT, tab_list TEXT, person_id TEXT, avatar_l TEXT)"];
    if (result) {
        NSLog(@"创建表成功");
    }
    else {
        NSLog(@"创建表失败");
    }
}
//插入收藏模型
- (void)insertExperienceWithModel:(ExperienceModel *)model{
    NSString *sql = [NSString stringWithFormat:@"INSERT INTO experienceTableChange(title_page, title, date_str, address, like_count, price, product_id, tab_list, person_id , avatar_l) VALUES('%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@', '%@')", model.title_page, model.title, model.date_str, model.address, model.like_count, model.price, model.product_id, [model.tab_list componentsJoinedByString:@","], model.anUser.person_id, model.anUser.avatar_l];
    BOOL result = [self.db executeUpdate:sql];
    if (result) {
        NSLog(@"插入成功");
    }
    else {
        NSLog(@"插入失败");
    }
}
//根据唯一的id删除收藏
- (void)deleteExperienceWithId:(NSString *)product_id{
    NSString *sql = [NSString stringWithFormat:@"DELETE FROM experienceTableChange WHERE product_id = '%@'", product_id];
    BOOL result = [self.db executeUpdate:sql];
    if (result) {
        NSLog(@"删除成功");
    }
    else{
        NSLog(@"删除失败");
    }
}
//返回收藏数组
- (NSMutableArray *)selectExperience{
    NSMutableArray *array = [NSMutableArray array];
    //1.执行查询语句
    FMResultSet *resultSet = [self.db executeQuery:@"SELECT * FROM experienceTableChange"];
    
    //遍历集合
    while ([resultSet next]) {
        
        ExperienceModel *model = [[ExperienceModel alloc] init];
        
        model.title_page = [resultSet objectForColumnName:@"title_page"];
        model.title = [resultSet objectForColumnName:@"title"];
        model.date_str = [resultSet objectForColumnName:@"date_str"];
        model.address = [resultSet objectForColumnName:@"address"];
        model.like_count = [resultSet objectForColumnName:@"like_count"];
        model.price = [resultSet objectForColumnName:@"price"];
        model.product_id = [resultSet objectForColumnName:@"product_id"];
        
        model.tab_list = [NSMutableArray arrayWithArray:[[resultSet objectForColumnName:@"tab_list"] componentsSeparatedByString:@","]];
        
        model.anUser = [[User alloc] init];
        model.anUser.person_id = [resultSet objectForColumnName:@"person_id"];
        model.anUser.avatar_l = [resultSet objectForColumnName:@"avatar_l"];
        
        [array addObject:model];
    }
    return array;
}

@end
